package com.efrei.uchat.io;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Observable;
import java.util.Observer;

import org.apache.log4j.Logger;

import com.efrei.uchat.message.Message;

public class MessageSender extends Observable implements Runnable {

	private static Logger logger = Logger.getLogger(MessageSender.class);
	
	private PrintWriter out;
	private Message message;

	public MessageSender(Observer context, Socket client, Message message) throws IOException {
		this.out = new PrintWriter(client.getOutputStream());
		this.message = message;
		addObserver(context);
	}
	
	@Override
	public void run() {
		logger.info("Send message to client: "+message.toString());
		try {
			out.println(message.toString());
			out.flush();
		} catch(Exception e) {
			e.printStackTrace();
			// send error to context
			setChanged();
			notifyObservers(e);
		}
	}
}
